import { TrackType, trackEvent } from '@/dataReport/tracks'
import {
  savePermanentInfo as savePermanentInfoAPI,
  getUserPermanentInfo as getUserPermanentInfoAPI,
} from '../../api/deviceMessageSubscribe'
import { showLoading } from '@/utils/mpHelper'
import { useGlobalStore } from '@/store/global'
const globalStore = useGlobalStore()

// const app = getApp()

// 返回模板id
const getTemplateIdList = (type: string | any[], itemSettings: WechatMiniprogram.IAnyObject) => {
  let templateId = []
  let k = 0

  for (let i = 0; i < type.length; i++) {
    if (type[i].type === 1) {
      k++
      if (k <= 3) templateId.push(type[i].templateId)
    }
  }
  return templateId
}
// 保存用户设备消息订阅信息
function savePermanentInfo(haId: string, miniProgramType: string, templateId: any, type: any) {
  savePermanentInfoAPI(haId, miniProgramType, templateId, type).then((res: any) => {})
}
// 比较后端保存的模板id状态和用户操作状态不同
function savePermanentInfoAcceptReject(haId: string, type: any, itemSettings: WechatMiniprogram.IAnyObject) {
  let templateIdAccept: any[] = []
  let templateIdReject: any[] = []
  type.forEach((item: { type: number; value: string; templateId: string }) => {
    if (item.type == 2) {
      item.value = 'reject'
    }
    if (item.type == 4) {
      item.value = 'accept'
    }
    for (const [key, value] of Object.entries(itemSettings)) {
      if (item.templateId == key && item.value != value) {
        if (value == 'accept') {
          templateIdAccept.push(key)
        }
        if (value == 'reject') {
          templateIdReject.push(key)
        }
      }
    }
  })
  if (templateIdAccept.length > 0) {
    savePermanentInfoAPI(haId, 'HC', templateIdAccept, 4)
  }
  if (templateIdReject.length > 0) {
    savePermanentInfoAPI(haId, 'HC', templateIdReject, 2)
  }
}

/**
 * 一次性消息订阅
 * @param tmplIds 消息模板的id的集合
 * @param callback
 */
export function orderOnceInfo(
  tmplIds: Array<string>
): Promise<UniNamespace.RequestSubscribeMessageSuccessCallbackResult> {
  return new Promise((resolve, reject) => {
    uni.requestSubscribeMessage({
      tmplIds: tmplIds,
      success(res) {
        resolve(res)
      },
      fail(error) {
        reject(error)
      },
    })
  })
}
/**
 *
 * @param that 永久消息订阅
 * @param haId
 * @param callback
 */
export function orderPermanentInfo(haId: string): Promise<void> {
  if (globalStore.is_virtual) {
    return new Promise(function (resolve, reject) {
      // 虚拟家电不进行数据请求
      return resolve()
    })
  }
  return new Promise((resolve, reject) => {
    uni.getSetting({
      withSubscriptions: true,
      success: async (resp) => {
        if (!resp.subscriptionsSetting.mainSwitch) {
          return resolve()
        }
        try {
          const res = await showLoading(() => getUserPermanentInfoAPI(haId, 'HC'))
          const { snTicket, sn, modelId, type } = res.data
          if (type === null || !type.length) {
            return resolve()
          }
          const itemSettings = resp.subscriptionsSetting.itemSettings
          if (itemSettings) {
            savePermanentInfoAcceptReject(haId, type, itemSettings)
          }

          const tmplIds = getTemplateIdList(type, itemSettings)

          if (!tmplIds.length) {
            return resolve()
          }
          // 设备长期订阅
          setTimeout(() => {
            uni.hideLoading()
          }, 1000)
          uni.requestSubscribeDeviceMessage({
            sn,
            snTicket,
            modelId,
            tmplIds,
            success(resMsg) {
              let templateIdList = []
              for (const [key, value] of Object.entries(resMsg)) {
                if (value == 'accept') {
                  templateIdList.push(key)
                }
              }
              try {
                trackEvent(
                  'subscribe_message',
                  { template_id: templateIdList.join(','), action_type: 'accept' },
                  TrackType.ApplianceDetail,
                  'BSH.Cpmmon.SubscribeMessage.Accept'
                )
              } catch (res) {
                console.error('用户埋点错误')
              }

              savePermanentInfoAPI(haId, 'HC', templateIdList, 4)
            },
            fail(resMsg: { errMsg: string | string[] }) {
              if (resMsg.errMsg.indexOf('reject') != -1) {
                uni.getSetting({
                  withSubscriptions: true,
                  success(result) {
                    let itemSettings = result.subscriptionsSetting.itemSettings as Record<string, string>
                    let templateIdLists: any[] = []
                    for (const [key, value] of Object.entries(itemSettings)) {
                      if (value == 'reject') {
                        templateIdLists.push(key)
                      }
                    }
                    try {
                      trackEvent(
                        'subscribe_message',
                        { template_id: templateIdLists.join(','), action_type: 'reject' },
                        TrackType.ApplianceDetail,
                        'BSH.Cpmmon.SubscribeMessage.Reject'
                      )
                    } catch (res) {
                      console.error('用户埋点错误')
                    }

                    savePermanentInfo(haId, 'HC', templateIdLists, 2)
                  },
                })
              } else if (resMsg.errMsg.indexOf('cancel') != -1) {
                trackEvent(
                  'subscribe_message',
                  { template_id: '', action_type: 'cancel' },
                  TrackType.ApplianceDetail,
                  'BSH.Cpmmon.SubscribeMessage.Cancel'
                )
              }
            },
            complete() {
              return resolve()
            },
          })
        } catch (e) {
          return reject(e)
        }
      },
      fail: (error) => {
        reject(error)
      },
    })
  })
}
